package com.southwind.utils;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by chenhs on 2018/6/27.
 */
public class MyInvocationHandler implements InvocationHandler {

    private String className;

    public Object getInstance(Class cls) {
        this.className = cls.getName();
        Object newProxyInstance = Proxy.newProxyInstance(cls.getClassLoader(), new Class[]{cls}, this);
        return (Object) newProxyInstance;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        SAXReader reader = new SAXReader();
        //返回结果
        Object obj = null;

        String xml = ParseXML.getMapperXML(this.className);
        Document document = reader.read(xml);
        Element root = document.getRootElement();

        Iterator iter = root.elementIterator();
        while (iter.hasNext()) {
            Element element = (Element) iter.next();
            String id = element.attributeValue("id");
            if (method.getName().equals(id)) {
                //获取C3P0信息，创建数据源对象
                Map<String, String> map = ParseXML.getC3P0Properties();
                ComboPooledDataSource dataSource = new ComboPooledDataSource();
                dataSource.setDriverClass(map.get("driver"));
                dataSource.setJdbcUrl(map.get("url"));
                dataSource.setUser(map.get("username"));
                dataSource.setPassword(map.get("password"));
                dataSource.setInitialPoolSize(20);
                dataSource.setMaxPoolSize(40);
                dataSource.setMinPoolSize(2);
                dataSource.setAcquireIncrement(5);
                Connection conn = dataSource.getConnection();

                //获取sql语句
                String sql = element.getText();
                //获取参数类型
                String parameterType = element.attributeValue("parameterType");
                //创建pstmt
                PreparedStatement pstmt = createPstmt(sql, parameterType, conn, args);
                ResultSet rs = pstmt.executeQuery();
                if (rs.next()) {
                    //获取返回值类型
                    String resultType = element.attributeValue("resultType");
                    //反射创建对象
                    Class clazz = Class.forName(resultType);
                    obj = clazz.newInstance();
                    //获取ResultSet数据
                    ResultSetMetaData rsmd = rs.getMetaData();
                    //遍历实体类属性集合，依次将结果集中的赋值给属性
                    Field[] fields = clazz.getDeclaredFields();
                    for (int i = 0; i < fields.length; i++) {
                        Object value = setFieldValueByResultSet(fields[i], rsmd, rs);
                        //通过属性名找到对应的setter方法
                        String name = fields[i].getName();
                        name = name.substring(0, 1).toUpperCase() + name.substring(1);
                        String methodName = "set" + name;
                        Method methodObj = clazz.getMethod(methodName, fields[i].getType());
                        //调用setter方法完成赋值
                        methodObj.invoke(obj, value);
                    }
                }
                conn.close();
            }
        }

        return obj;
    }

    /**
     * 根据条件创建psmt
     *
     * @param sql
     * @param parameterType
     * @param conn
     * @param args
     * @return
     * @throws Exception
     */
    public PreparedStatement createPstmt(String sql, String parameterType, Connection conn, Object[] args) throws Exception {
        PreparedStatement psmt = null;
        try {
            switch (parameterType) {
                case "int":
                    int start = sql.indexOf("#{");
                    int end = sql.indexOf("}");
                    //获取参数占位符#{name}
                    String target = sql.substring(start, end + 1);
                    //将占位符替换为?
                    sql = sql.replace(target, "?");
                    psmt = conn.prepareStatement(sql);
                    int num = Integer.parseInt(args[0].toString());
                    psmt.setInt(1, num);
                    break;
                case "java.lang.String":
                    int start2 = sql.indexOf("#{");
                    int end2 = sql.indexOf("}");
                    //获取参数占位符#{name}
                    String target2 = sql.substring(start2, end2 + 1);
                    //将占位符替换为?
                    sql = sql.replace(target2, "?");
                    psmt = conn.prepareStatement(sql);
                    String str = args[0].toString();
                    psmt.setString(1, str);
                    break;
                default:
                    Class clazz = Class.forName(parameterType);
                    Object obj = args[0];
                    boolean flag = true;
                    //存储参数
                    List<Object> values = new ArrayList<Object>();
                    //保存带#的sql
                    String sql2 = "";
                    while (flag) {
                        int start3 = sql.indexOf("#{");
                        if (start3 < 0) {
                            flag = false;
                            break;
                        }
                        int end3 = sql.indexOf("}");
                        String target3 = sql.substring(start3, end3 + 1);
                        //获取#{}的值，如#{name}拿到name
                        String name = sql.substring(start3 + 2, end3);
                        //通过反射获取对应的getter方法
                        name = name.substring(0, 1).toUpperCase() + name.substring(1);
                        String methodName = "get" + name;
                        Method methodObj = clazz.getMethod(methodName);
                        //调用getter方法完成赋值
                        Object value = methodObj.invoke(obj);
                        values.add(value);
                        sql = sql.replace(target3, "?");
                        sql2 = sql.replace("?", "#");
                    }
                    //截取sql2，替换参数
                    String[] sqls = sql2.split("#");
                    for (int i = 0; i < sqls.length - 1; i++) {
                        Object value = values.get(i);
                        if ("java.lang.String".equals(value.getClass().getName())){
                            psmt.setString(i+1, (String) value);
                        }
                        if ("java.lang.Integer".equals(value.getClass().getName())){
                            psmt.setInt(i+1, (Integer) value);
                        }
                    }
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return psmt;
    }

    /**
     * 将结果集中的值赋给对应的属性
     *
     * @param field
     * @param rsmd
     * @param rs
     * @return
     */
    public Object setFieldValueByResultSet(Field field, ResultSetMetaData rsmd, ResultSet rs) {
        Object result = null;

        try {
            boolean match = false;
            int count = rsmd.getColumnCount();
            for (int i = 1; i <= count; i++) {
                String columnName = rsmd.getColumnName(i);
                if (field.getName().equals(columnName)) {
                    match = true;
                    String type = field.getType().getName();
                    switch (type) {
                        case "int":
                            result = rs.getInt(field.getName());
                            break;
                        case "java.lang.Integer":
                            result = rs.getInt(field.getName());
                            break;
                        case "java.lang.String":
                            result = rs.getString(field.getName());
                            break;
                        default:
                            break;
                    }
                }
                if (match) break;   //跳出for循环
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return result;
    }
}
